package com.vito.framework.base.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.vito.framework.cache.CacheKeys;
import com.vito.framework.cache.ICache;
import com.vito.framework.rest.bean.AppSession;
import com.vito.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/***************************************************************
 * Name:        BaseController.java
 * Create At:   2017-04-22
 * Module:      公用Controller
 * Description: [各模块Controller必须继承此类，用于全局的封装]
 * Author       zhaowentao
 * ------------------------------------------------------------
 * 修改历史
 * 序号  日期  修改人   修改原因
 * 1
 * 2
***************************************************************/
@Slf4j
public abstract class BaseController{

    /**
     * 管理基础路径
     */
    @Value("${adminPath}")
    protected String adminPath;

    /**
     * api基础路径
     */
    @Value("${restPath}")
    protected String restPath;

    /**
     * 前端URL后缀
     */
    @Value("${urlSuffix}")
    protected String urlSuffix;

	@Autowired
	protected ICache cacheUtil;
	/**
	 * Author:zhaowentao
     * Create At:2010-04-22
     * Description: [初始化请求]
	 * @throws IllegalAccessException
     */
	@ModelAttribute
    protected void handle(HttpServletRequest request,HttpServletResponse response) throws Exception {

    }

    protected Map<String, Object> getParamMap(HttpServletRequest request, JSONObject params) {
	    Map<String, Object> paramMap = JSONObject.toJavaObject(params, Map.class);
	    AppSession appSession = getUserSession(request);
    	if(appSession!=null){
    		paramMap.put("cur_orgId", appSession.getMerchantId());
    		paramMap.put("cur_userId", appSession.getUserId());
    		paramMap.put("cur_userName", appSession.getUserName());
    	}

	    if(!StrUtil.isEmpty(params.getString("param_keyword"))){
	    	String value = params.getString("param_keyword");
		    value = value.replace("%", "\\%");
		    value = value.replace("_", "\\_");
		    paramMap.put("param_keyword", value);
	    }

	    if (params.getIntValue("page_num") > 0 && params.getIntValue("page_size") > 0) {
	    	int page_num = params.getIntValue("page_num");
	    	int page_size = params.getIntValue("page_size");

	    	paramMap.put("param_curpage", (page_num - 1) * page_size);
	    	paramMap.put("param_ipagecount", page_size);
	    }
	    return paramMap;
    }

    /**
     * @Description：获取访问用户会话ID
     * @param request
     * @return String
     */
    public String getSessionId(HttpServletRequest request) {
    	String apptoken = request.getHeader(CacheKeys.APP_TOKEN);
    	if(StrUtil.isEmpty(apptoken)) {
        	apptoken = CookieUtil.getCookieValue(request, CacheKeys.USER_TOKEN);
        }
    	return apptoken;
    }

    /**
     * @Description：获取访问用户权限
     * @param request
     * @return appSession
     */
    public AppSession getUserSession(HttpServletRequest request) {
        String token = getSessionId(request);
		AppSession appSession = (AppSession)request.getSession().getAttribute(CacheKeys.APP_TOKEN + token);
		if(appSession == null) {
			appSession = cacheUtil.get(CacheKeys.APP_TOKEN + token);
		}
        return appSession;
    }

    /**
     * @Description：设置访问用户权限
     * @param request
     * @param appSession
     * @return void
     */
    public void setUserSession(HttpServletRequest request, AppSession appSession) {
		if(appSession != null && request.getSession() != null) {
			request.getSession().setAttribute(CacheKeys.APP_TOKEN + appSession.getSessionId(),appSession);
		}
        cacheUtil.put(CacheKeys.APP_TOKEN + appSession.getSessionId(), appSession , CacheKeys.USER_TOKEN_EXPIRETIME);
    }


}
